// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use std::fs;
use std::path::Path;
use std::time::SystemTime;
use log::info;

#[derive(serde::Serialize)]
struct FileInfo {
    name: String,
    size: u64,
    modified: SystemTime,
    is_dir: bool,
}

#[tauri::command]
fn get_drives() -> Vec<String> {
    // 读取 Windows 系统的所有磁盘（如 C:\、D:\）
    let drives = [
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
        'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    ];
    drives
        .iter()
        .filter_map(|&drive| {
            let path = format!("{}:\\", drive);
            if fs::metadata(&path).is_ok() {
                Some(path)
            } else {
                None
            }
        })
        .collect()
}

#[tauri::command]
fn get_folder_info(path: String) -> Result<Vec<FileInfo>, String> {
    let mut file_infos = Vec::new();
    let dir = Path::new(&path);

    if dir.is_dir() {
        for entry in fs::read_dir(dir).map_err(|e| e.to_string())? {
            let entry = entry.map_err(|e| e.to_string())?;
            let metadata = entry.metadata().map_err(|e| e.to_string())?;
            let file_info = FileInfo {
                name: entry
                    .file_name()
                    .into_string()
                    .map_err(|e| e.to_string_lossy().to_string())?,
                size: metadata.len(),
                modified: metadata.modified().map_err(|e| e.to_string())?,
                is_dir: metadata.is_dir(),
            };
            file_infos.push(file_info);
        }
        Ok(file_infos)
    } else {
        Err("Path is not a directory".to_string())
    }
}

#[tauri::command]
fn rename_folder(old_path: String, new_path: String) -> Result<(), String> {
    let old_folder_path = Path::new(&old_path);
    let new_folder_path = Path::new(&new_path);

    match fs::rename(old_folder_path, new_folder_path) {
        Ok(_) =>Ok(()),
        Err(e) => Err(format!("Failed to rename folder: {}", e))
    }
}

fn main() {
    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![
            get_drives,
            get_folder_info,
            rename_folder,
        ]) // 注册Rust命令
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
